<?php


namespace app\common\lib;

use app\common\cachemodel\Orders as OrdersCacheModel;
use app\common\cachemodel\OrdersLib;
use app\common\cachemodel\privatearea\PrivateAreaOrders;
use think\Log;
use think\queue\Job;
use think\response\Json;

class CloseOrderJob
{
    /**
     * 检测订单关闭
     * @param Job $job
     * @param $jobData
     * @return bool|Json
     */
    public function task1(Job $job, $jobData)
    {
        if ($job->attempts() > 1)
        {
            $job->delete();
        }
        Log::write('关闭订单开始时间：' . date('Y-m-d H:i:s'), 'log', true);

        try
        {
            $OrdersLib = new OrdersLib();
            $num = $this->check_type($jobData['order_id']);
            if (in_array($num, [51, 52, 53, 54, 55, 56, 57], true))
            {
                $orderInfo = (new PrivateAreaOrders())->getInfoById($jobData['order_id'], ['status', 'qid', 'order_id']);
                if ($orderInfo['status'] === 1)
                {   // 1=>待支付 2=>待解答 3=>未支付订单关闭 4=>已完成 5=>已退款
                    if ($num === 57)
                    {   //  私域实物
                        $OrdersLib::privateAreaMallCloseOrder($orderInfo);
                    } else
                    {
                        $OrdersLib::privateAreaCloseOrder($orderInfo);
                    }
                }
            } else
            {
                $orderModel = new OrdersCacheModel();
                //获取
                $orders = $orderModel->where(['order_id' => $jobData['order_id']])->column('uid,order_id,create_time,extend,fid,status,order_type,gid', 'id');
                foreach ($orders as $order)
                {
                    if ((int)$order['status'] === 0)
                    {   // 待支付订单 关闭订单
                        $OrdersLib::CloseOrder($order, 1, '系统超时关闭');
                    }
                }
            }
            $job->delete();
        }
        catch (\Exception $e)
        {
            Log::write('关闭订单问题：' . $e->getMessage() . json_encode($jobData) . PHP_EOL . '错误行数：' . '[' . $e->getFile() . ':' . $e->getLine() . ']', 'error', true);
        }
        Log::write('关闭订单结束时间：' . date('Y-m-d H:i:s'), 'log', true);
    }

    /**
     * 判断订单类型
     * @param $order_id
     * @return int
     */
    private function check_type($order_id): int
    {

        $num = substr($order_id, 0, 2);

        return (int)$num;
    }
}
